import 'package:flutter_study/review/reudx2/redux_state.dart';
import 'package:redux/redux.dart';

import 'user.dart';

// 将函数和action绑定，action执行对象的函数
// 避免了多个Reducer、Action造成函数的冗余
// 各自的Reducer处理各自的逻辑
final UserReducer = combineReducers<User>([
  TypedReducer<User, AddUserAction>(_add),
  TypedReducer<User, UpdateUserAction>(_update),
]);

// 定义要与AddUserAction绑定的函数，替代之前if else的判断
User _add(User user, AddUserAction addUserAction) {
  addUserAction.user.name = user.name + "a";
  user = addUserAction.user;
  return user;
}

User _update(User user, UpdateUserAction updateUserAction) {
  updateUserAction.user.name = "update fauks";
  user = updateUserAction.user;
  return user;
}

// 定义action
class AddUserAction {
  User user;

  AddUserAction(this.user);
}

class UpdateUserAction {
  User user;

  UpdateUserAction(this.user);
}

// 定义中间件有点类似拦截器
class UserInfoMiddleware1 implements MiddlewareClass<ReduxState> {
  @override
  call(Store<ReduxState> store, action, next) {
    print('执行中间件1');
    if (action is AddUserAction) {
      print('拦截到Add user');
    } else if (action is UpdateUserAction) {
      print('拦截到 Update user');
    }

    // 调用next方法放行中间件，如果不调用则不往下执行
    next(action);
  }
}
